﻿using DoNet.Common.Extensions;
using DoNet.Common.Helpers;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using RabbitMQ.Client;

namespace DoNet.EventBus.RabbitMQ
{
    /// <summary>
    /// RabbitMQ启动服务
    /// </summary>
    public static class RabbitMQSetup
    {
        /// <summary>
        /// RabbitMQ启动服务
        /// </summary>
        /// <param name="services"></param>
        /// <exception cref="ArgumentNullException"></exception>
        public static void AddRabbitMQSetup(this IServiceCollection services, IConfiguration config)
        {
            if (services == null) throw new ArgumentNullException(nameof(services));

            if (config.app("EventBus:RabbitMQ:Enabled").ObjectToBool())
            {
                services.AddSingleton<IRabbitMQPersistentConnection>(sp =>
                {
                    var logger = sp.GetRequiredService<ILogger<DefaultRabbitMQPersistentConnection>>();

                    var factory = new ConnectionFactory();
                    if (!string.IsNullOrEmpty(config.app("EventBus:RabbitMQ:Connection").ObjectToString()))
                    {
                        factory.UserName = config.app("EventBus:RabbitMQ:Connection").ObjectToString();
                    }

                    //factory.DispatchConsumersAsync = true;
                    if (!string.IsNullOrEmpty(config.app("EventBus:RabbitMQ:UserName").ObjectToString()))
                    {
                        factory.UserName = config.app("EventBus:RabbitMQ:UserName").ObjectToString();
                    }
                    if (!string.IsNullOrEmpty(config.app("EventBus:RabbitMQ:Password").ObjectToString()))
                    {
                        factory.Password = config.app("EventBus:RabbitMQ:Password").ObjectToString();
                    }
                    if (!string.IsNullOrEmpty(config.app("EventBus:RabbitMQ:Port").ObjectToString()))
                    {
                        factory.Port = config.app("EventBus:RabbitMQ:Port").ObjectToInt();
                    }
                    var retryCount = 5;
                    if (!string.IsNullOrEmpty(config.app("EventBus:RabbitMQ:RetryCount")))
                    {
                        retryCount = config.app("EventBus:RabbitMQ:RetryCount").ObjectToInt();
                    }
                    return new DefaultRabbitMQPersistentConnection(factory, logger, retryCount);
                });
            }
        }
    }
}
